package com.sky.task;

import com.sky.dto.OrdersPageQueryDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理超时订单
     * 执行时机：每分钟一次
     * 执行任务：扫描数据库，找出超时未支付的订单，取消订单
     */
    @Scheduled(fixedRate = 1000*60)
    public void processTimeoutOrder(){
        //1. 查找超时未支付的订单：15分钟前下单，状态是待付款的订单
        OrdersPageQueryDTO dto = new OrdersPageQueryDTO();
        dto.setStatus(Orders.PENDING_PAYMENT);
        dto.setEndTime(LocalDateTime.now().minusMinutes(15));
        List<Orders> ordersList = orderMapper.pageQueryH(dto);
        if (ordersList != null && ordersList.size()>0) {
            //取消订单
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("超时未支付，自动取消订单");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.updateOrders(orders);
                log.info("订单{}下单时间：{}，超时未支付，已自动取消", orders.getId(), orders.getOrderTime());
            }
        }
    }
    /**
     * 处理“派送中”的订单
     * 执行时机：每天凌晨1点整
     * 执行任务：扫描数据库，找出派送中的订单，设置为“已完成”
     */
    //每天15.45
    @Scheduled(cron = "0 51 15 * * ?")
    public void processDeliveryOrder(){
        //1.查询派送中的订单
        //创建容器
        OrdersPageQueryDTO dto = new OrdersPageQueryDTO();
        //设置状态为派送中
        dto.setStatus(Orders.DELIVERY_IN_PROGRESS);
        List<Orders> ordersList = orderMapper.pageQueryH(dto);
        //2. 如果有，就修改这些订单的状态
        if (ordersList != null && ordersList.size()>0) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.updateOrders(orders);
                log.info("订单{}派送时间：{},派送已超时，自动完成",orders.getId(),orders.getDeliveryTime());
            }
        }
    }
}
